package com.qny.ai.controller;

import com.qny.ai.common.ApiResponse;
import com.qny.ai.service.impl.KodoStorageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Base64;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/upload")
@RequiredArgsConstructor
public class FileUploadController {

    private final KodoStorageService kodoStorageService;

    /**
     * 上传头像
     */
    @PostMapping("/avatar")
    public ApiResponse<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return ApiResponse.fail(400, "文件不能为空");
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ApiResponse.fail(400, "只支持图片文件");
            }
            
            // 验证文件大小 (5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                return ApiResponse.fail(400, "文件大小不能超过5MB");
            }
            
            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String ext = "jpg"; // 默认扩展名
            if (originalFilename != null && originalFilename.contains(".")) {
                ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            }
            
            // 生成唯一文件名
            String fileName = "avatar/" + java.time.LocalDate.now() + "/" + UUID.randomUUID() + "." + ext;
            
            // 上传到Kodo
            byte[] fileData = file.getBytes();
            String url = kodoStorageService.uploadBytes(fileData, ext);
            
            log.info("[FILE_UPLOAD] Avatar uploaded successfully: {}", url);
            return ApiResponse.ok(url);
            
        } catch (Exception e) {
            log.error("[FILE_UPLOAD] Avatar upload failed: ", e);
            return ApiResponse.fail(500, "头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传Base64编码的图片
     */
    @PostMapping("/avatar/base64")
    public ApiResponse<String> uploadAvatarBase64(@RequestBody AvatarUploadRequest request) {
        try {
            if (request.getBase64Data() == null || request.getBase64Data().trim().isEmpty()) {
                return ApiResponse.fail(400, "Base64数据不能为空");
            }
            
            // 解析Base64数据
            String base64Data = request.getBase64Data();
            if (base64Data.contains(",")) {
                base64Data = base64Data.substring(base64Data.indexOf(",") + 1);
            }
            
            // 解码Base64数据
            byte[] imageData = Base64.getDecoder().decode(base64Data);
            
            // 验证文件大小
            if (imageData.length > 5 * 1024 * 1024) {
                return ApiResponse.fail(400, "文件大小不能超过5MB");
            }
            
            // 获取文件扩展名
            String ext = request.getExt() != null ? request.getExt() : "jpg";
            
            // 上传到Kodo
            String url = kodoStorageService.uploadBytes(imageData, ext);
            
            log.info("[FILE_UPLOAD] Base64 avatar uploaded successfully: {}", url);
            return ApiResponse.ok(url);
            
        } catch (Exception e) {
            log.error("[FILE_UPLOAD] Base64 avatar upload failed: ", e);
            return ApiResponse.fail(500, "头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 头像上传请求DTO
     */
    public static class AvatarUploadRequest {
        private String base64Data;
        private String ext;

        public String getBase64Data() {
            return base64Data;
        }

        public void setBase64Data(String base64Data) {
            this.base64Data = base64Data;
        }

        public String getExt() {
            return ext;
        }

        public void setExt(String ext) {
            this.ext = ext;
        }
    }
}

